package com.test.dababy.dababy_07_loan_status;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.test.dababy.R;
import com.test.dababy.dababy_00_customer_service.Customer_dababyServiceDialog;
import com.test.dababy.dababy_04_home.MainAct_dababyivity;
import com.test.dababy.dababy_01_launcher.App_dababyShow_dababyCustomize;
import com.test.dababy.dababy_01_launcher.Recommend_dababyAppInfo;
import com.test.dababy.dababy_05_process.Pro_dababycessIn_dababyfo;
import com.test.dababy.dababy_05_process.Acc_dababyountLi_dababyst_Fr;
import com.test.dababy.dababy_05_process.Ba_dababynkAcc_dababyount_Fr;
import com.test.dababy.dababy_06_loan_apply.LoanApplyDetail;
import com.test.dababy.Othe_dababyrsInfo;
import com.test.dababy.dababy_05_process.Bin_dababydAcco_dababyuntChannelDialog_Fr;
import com.test.dababy.dababy_05_process.Bin_dababydAccount_dababyDialog_Fr;
import com.test.dababy.dababy_05_process.Delete_dababyAccountDi_dababyalog_Fr;
import com.test.dababy.dababy_00_http.OkHttpUtil;
import com.test.dababy.dababy_00_utils.DababyUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class LoanSta_dababyteWaitFra_dababygment extends BaseLoanFragment {


    private String vnRY="";
    private float qsQu=0.7003647f;
    private int sVgp=42;
    private boolean b409=false;
    private String brUe="";
    private String bJJI="";
    private String lY4Q="";
    private String eD5Q="";
    private String e61D="";
    private float fOE3=0.9546746f;
    private String vGza="";

    public void vOZzV(){
        new Thread(() -> {
            try {

                if (TextUtils.isEmpty(getVnRY())) setVnRY(getbJJI()+getQsQu()+getsVgp()+isB409());
                else setBrUe(getlY4Q()+geteD5Q()+getE61D()+getfOE3()+getvGza());

            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }

    public void setVnRY(String vnRY) {
        this.vnRY = vnRY;
    }

    public void setQsQu(float qsQu) {
        this.qsQu = qsQu;
    }

    public void setsVgp(int sVgp) {
        this.sVgp = sVgp;
    }

    public void setB409(boolean b409) {
        this.b409 = b409;
    }

    public void setBrUe(String brUe) {
        this.brUe = brUe;
    }

    public void setbJJI(String bJJI) {
        this.bJJI = bJJI;
    }

    public void setlY4Q(String lY4Q) {
        this.lY4Q = lY4Q;
    }

    public void seteD5Q(String eD5Q) {
        this.eD5Q = eD5Q;
    }

    public void setE61D(String e61D) {
        this.e61D = e61D;
    }

    public void setfOE3(float fOE3) {
        this.fOE3 = fOE3;
    }

    public void setvGza(String vGza) {
        this.vGza = vGza;
    }

    public String getVnRY() {
        return vnRY;
    }

    public float getQsQu() {
        return qsQu;
    }

    public int getsVgp() {
        return sVgp;
    }

    public boolean isB409() {
        return b409;
    }

    public String getBrUe() {
        return brUe;
    }

    public String getbJJI() {
        return bJJI;
    }

    public String getlY4Q() {
        return lY4Q;
    }

    public String geteD5Q() {
        return eD5Q;
    }

    public String getE61D() {
        return e61D;
    }

    public float getfOE3() {
        return fOE3;
    }

    public String getvGza() {
        return vGza;
    }

    private SwipeRefreshLayout refreshLayout;
    private ImageButton csIb;
    private ImageView statusIv;
    private TextView statusTv1,statusTv2;
    private Button refreshBtn;
    private TextView loanAmountTv,loanTermTv;
    private LinearLayout accountGroupLayout,recommendGroupLayout;
    private View recommendView;

    private View tipsView;
    private TextView tipsTitleTv,tipsTv;

    private String bindChannelMobile_dababy = "";

    private static String TAG = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dababy_loan_state_wait, container, false);

        refreshLayout = view.findViewById(R.id.fldw_refreshlayout);
        csIb = view.findViewById(R.id.fldw_ib_cs);
        statusIv = view.findViewById(R.id.fldw_iv_status);
        statusTv1 = view.findViewById(R.id.fldw_tv_status_1);
        statusTv2 = view.findViewById(R.id.fldw_tv_status_2);
        refreshBtn = view.findViewById(R.id.fldw_btn_refresh);
        loanAmountTv = view.findViewById(R.id.fldw_tv_loan_amount);
        loanTermTv = view.findViewById(R.id.fldw_tv_loan_term);
        accountGroupLayout = view.findViewById(R.id.fldw_layout_account_group);
        recommendGroupLayout = view.findViewById(R.id.fldw_layout_recommend_group);
        recommendView = view.findViewById(R.id.fldw_view_recommend);

        tipsView = view.findViewById(R.id.fldw_view_tips);
        tipsTitleTv = view.findViewById(R.id.fldw_tv_tips_title);
        tipsTv = view.findViewById(R.id.fldw_tv_tips);


        csIb.setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"CUSTOMER_SERVICE_CLICK","");
            new Customer_dababyServiceDialog(requireContext()).show();
        });

        //两个刷新控件
        refreshBtn.setOnClickListener(v -> {

            DababyUtil.startLoading(requireContext(),"");

            OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"REFRESH_CLICK","");

            OkHttpUtil.getInstance_dababy().requestUsPrcs(() -> {
                String state = Pro_dababycessIn_dababyfo.getInstance_dababy().getDababyUtil();
                if (DababyUtil.isStateChange_dababy(state)) {//刷新用户状态
                    DababyUtil.stopLoading();
                    FragmentActivity activity = requireActivity();
                    DababyUtil.clearState_dababy();
                    activity.startActivity(new Intent(activity, MainAct_dababyivity.class));
                    activity.finish();
                }else {
                    OkHttpUtil.getInstance_dababy().fetchLnAplDetail(() -> OkHttpUtil.getInstance_dababy().fetchLauncherConfig(this::refreshLoanDetail));
                }
            });

        });

        refreshLayout.setOnRefreshListener(() -> {

            refreshLayout.setRefreshing(false);

            DababyUtil.startLoading(requireContext(),"");

            OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"REFRESH_PULL","");

            OkHttpUtil.getInstance_dababy().requestUsPrcs(() -> {
                String state = Pro_dababycessIn_dababyfo.getInstance_dababy().getDababyUtil();
                if (DababyUtil.isStateChange_dababy(state)) {//刷新用户状态
                    DababyUtil.stopLoading();
                    FragmentActivity activity = requireActivity();
                    DababyUtil.clearState_dababy();
                    activity.startActivity(new Intent(activity, MainAct_dababyivity.class));
                    activity.finish();
                }else {
                    OkHttpUtil.getInstance_dababy().fetchLnAplDetail(() -> OkHttpUtil.getInstance_dababy().fetchLauncherConfig(this::refreshLoanDetail));
                }
            });

        });

        init_dababy();

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        DababyUtil.startLoading(requireContext(),"");
        OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"START","");
        OkHttpUtil.getInstance_dababy().fetchLnAplDetail(() ->
                OkHttpUtil.getInstance_dababy().fetchLauncherConfig(this::refreshLoanDetail)
        );
    }

    private void init_dababy(){
        //状态：审核通过放款中
        if (Pro_dababycessIn_dababyfo.getInstance_dababy().isOrderLoaning_dababy()){
            TAG = "LOANING";
            statusIv.setBackgroundResource(R.drawable.img_loan_status_loaning);
            statusTv1.setText(getString(R.string.loan_wait_loaning_text_1));
            statusTv2.setText(getString(R.string.loan_wait_loaning_text_2));
            vOZzV();
        }

        //状态：审核中
        else {
            TAG = "REVIEW";
            statusIv.setBackgroundResource(R.drawable.img_loan_status_review);
            statusTv1.setText(getString(R.string.loan_wait_review_text_1));
            statusTv2.setText(getString(R.string.loan_wait_review_text_2));
        }

        //产品配置
        refreshDababyInfo();

    }

    //更新提示文案和推荐App
    private void refreshDababyInfo(){

        //提示文案初始化
        if (App_dababyShow_dababyCustomize.getInstance_dababy().isShowWaitTips()){
            tipsView.setVisibility(View.VISIBLE);
            String title = App_dababyShow_dababyCustomize.getInstance_dababy().getWaitTipsTitle();
            String content = App_dababyShow_dababyCustomize.getInstance_dababy().getWaitTipsText();
            if (!TextUtils.isEmpty(title)) tipsTitleTv.setText(title);
            tipsTv.setText(content);
        }else tipsView.setVisibility(View.GONE);

        //app推荐显示
        refreshRecommendApps();
    }

    //更新额度、日期、绑卡列表
    @SuppressLint("SetTextI18n")
    public void refreshLoanDetail(){

        String currency = LoanApplyDetail.getInstance_dababy().getCurrency_dababy();

        loanAmountTv.setText(LoanApplyDetail.getInstance_dababy().getAmount_dababy()+" "+currency);
        loanTermTv.setText(LoanApplyDetail.getInstance_dababy().getTermStr_dababy());

        //放款账户显示
        refreshAccounts_dababy();
    }

    //更新推荐App显示
    public void refreshRecommendApps(){
        if (!App_dababyShow_dababyCustomize.getInstance_dababy().getRecommendFlag_dababy()) {
            recommendView.setVisibility(View.GONE);
            return;
        }

        recommendView.setVisibility(View.VISIBLE);

        recommendGroupLayout.removeAllViews();
        ArrayList<Recommend_dababyAppInfo> recommendAppInfos = App_dababyShow_dababyCustomize.getInstance_dababy().getRecommendAppList_dababy();
        for (Recommend_dababyAppInfo recommendAppInfo:recommendAppInfos){
            addRecommendApp_dababy(recommendAppInfo);
        }
    }

    //添加推荐App
    private void addRecommendApp_dababy(Recommend_dababyAppInfo recommendAppInfo){
        View itemView = LayoutInflater.from(requireContext()).inflate(R.layout.item_dababy_recommend_app,null);

        ImageView appLogoIv = itemView.findViewById(R.id.idra_iv_app_logo);
        TextView appNameTv = itemView.findViewById(R.id.idra_tv_app_name);
        TextView appAmountTv = itemView.findViewById(R.id.idra_tv_app_amount);
        TextView appRateTv = itemView.findViewById(R.id.idra_tv_app_rate);
        TextView appDownloadTv = itemView.findViewById(R.id.idra_tv_app_download);
        View installBtn = itemView.findViewById(R.id.idra_btn_install);

        appNameTv.setText(recommendAppInfo.getAp_dababypName());
        appAmountTv.setText(recommendAppInfo.getAmou_dababyntText());
        appRateTv.setText(recommendAppInfo.getSc_dababyore());
        appDownloadTv.setText(recommendAppInfo.getDow_dababynloads());

        //Install按键
        installBtn.setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"RECOMMEND_"+recommendAppInfo.getAp_dababypName().toUpperCase()+"_INSTALL_CLICK","");
            String path = recommendAppInfo.getP_dababyath();
            if (!TextUtils.isEmpty(path))
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(path)));
        });

        //加载logo
        if (recommendAppInfo.getLogo_dababyBitmap()==null){
            new Thread(() -> {
                try {
                    String logoPath = recommendAppInfo.getL_dababyogo();
                    if (TextUtils.isEmpty(logoPath)) return;
                    URL url = new URL(logoPath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        recommendAppInfo.setLo_dababygoB_dababyitmap(bitmap);
                        DababyUtil.safeRun(() -> appLogoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else appLogoIv.setImageBitmap(recommendAppInfo.getLogo_dababyBitmap());

        recommendGroupLayout.addView(itemView);
    }

    //放款账户显示
    private void refreshAccounts_dababy(){

        accountGroupLayout.removeAllViews();

        if (DababyUtil.isGhana_dababy()){//加纳

            DababyUtil.stopLoading();

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_dababy_account_show,null);
            TextView accountTv = accountView.findViewById(R.id.iasa_tv_account);
            accountTv.setText(LoanApplyDetail.getInstance_dababy().getWltMobile_Gh_dababy());
            accountGroupLayout.addView(accountView);
            fetchRateWindowConfig();

        }else if (DababyUtil.isFrench_dababy()){//法语区

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_dababy_account_show_fr,null);

            LinearLayout itemGroupLayout = accountView.findViewById(R.id.idasf_layout_group);
            View addAccountBtn = accountView.findViewById(R.id.idasf_view_add_btn);

            addAccountBtn.setOnClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"ADD_CLICK","");
                new Bin_dababydAccount_dababyDialog_Fr(requireActivity(), TAG,
                        mobile -> {
                            bindChannelMobile_dababy = mobile;
                            OkHttpUtil.getInstance_dababy().fetchWalletAccountList_fr(() -> refreshAccountList_Fr_dababy(itemGroupLayout));
                        }
                ).show();
            });

            accountGroupLayout.addView(accountView);

            OkHttpUtil.getInstance_dababy().fetchWalletAccountList_fr(() -> refreshAccountList_Fr_dababy(itemGroupLayout));

        }else {//其他国家

            DababyUtil.stopLoading();

            View accountView = LayoutInflater.from(requireContext()).inflate(R.layout.item_dababy_account_show,null);
            TextView accountTv = accountView.findViewById(R.id.iasa_tv_account);
            accountTv.setText(LoanApplyDetail.getInstance_dababy().getBkAccount_NiUgKe_dababy());
            accountGroupLayout.addView(accountView);
            fetchRateWindowConfig();

        }
    }

    //更新法语区绑卡列表
    public void refreshAccountList_Fr_dababy(LinearLayout itemGroupLayout){

        DababyUtil.stopLoading();

        if (itemGroupLayout == null) return;

        itemGroupLayout.removeAllViews();

        for (Ba_dababynkAcc_dababyount_Fr account: Acc_dababyountLi_dababyst_Fr.getInstance_dababy().getBankAccountList_dababy()){
            addAccount_Fr_dababy(itemGroupLayout,account);
        }

        //更新列表后，判断是否需要绑定运营商
        if (!TextUtils.isEmpty(bindChannelMobile_dababy) ){
            if (Othe_dababyrsInfo.getInstance_dababy().getAddBindFlag_dababy()){
                new Bin_dababydAcco_dababyuntChannelDialog_Fr(
                        requireContext(),
                        bindChannelMobile_dababy,
                        null,
                        () -> {
                            OkHttpUtil.getInstance_dababy().addWalletAccount_Fr(
                                    bindChannelMobile_dababy,
                                    bindChannelMobile_dababy,
                                    Othe_dababyrsInfo.getInstance_dababy().getChannel_dababy(),
                                    () -> OkHttpUtil.getInstance_dababy().fetchWalletAccountList_fr(() -> refreshAccountList_Fr_dababy(itemGroupLayout)),
                                    false
                            );
                        }
                ).show();
                bindChannelMobile_dababy = "";
            }
        }else fetchRateWindowConfig();
    }

    //法语区添加放款卡
    private void addAccount_Fr_dababy(LinearLayout itemGroupLayout,Ba_dababynkAcc_dababyount_Fr account){
        if (account == null || itemGroupLayout == null) return;

        String desc = account.getWalletDesc_dababy();

        View accountView = View.inflate(requireContext(), R.layout.item_dababy_account_fr, null);
        TextView titleTv = accountView.findViewById(R.id.idaf_tv_title);
        ImageView logoIv = accountView.findViewById(R.id.idaf_iv_logo);
        TextView channelTv = accountView.findViewById(R.id.idaf_tv_channel);
        TextView mobileTv = accountView.findViewById(R.id.idaf_tv_mobile);
        ImageButton deleteIb = accountView.findViewById(R.id.idaf_ib_delete);

        titleTv.setVisibility(View.GONE);
        mobileTv.setText(account.getWalletMobile_dababy());
        channelTv.setText(desc);

        //删除卡
        deleteIb.setOnClickListener(v -> {
            OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"DELETE_CLICK",account.getWalletMobile_dababy());
            new Delete_dababyAccountDi_dababyalog_Fr(requireActivity(),account, TAG,
                    () -> OkHttpUtil.getInstance_dababy().fetchWalletAccountList_fr(() -> refreshAccountList_Fr_dababy(itemGroupLayout))).show();
        });

        itemGroupLayout.addView(accountView);

        //获取图标
        if (App_dababyShow_dababyCustomize.getInstance_dababy().getChannelLogoByDesc_dababy(desc) == null){
            new Thread(() -> {
                try {
                    if (TextUtils.isEmpty(account.getWalletLogo_dababy())) return;
                    if (!App_dababyShow_dababyCustomize.getInstance_dababy().hasAccountChannel_dababy()) return;
                    URL url = new URL(account.getWalletLogo_dababy());
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("GET");
                    if (connection.getResponseCode()==200){
                        InputStream inputStream = connection.getInputStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        App_dababyShow_dababyCustomize.getInstance_dababy().setChannelLogoByDesc_dababy(desc,bitmap);
                        DababyUtil.safeRun(() -> logoIv.setImageBitmap(bitmap));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }else logoIv.setImageBitmap(App_dababyShow_dababyCustomize.getInstance_dababy().getChannelLogoByDesc_dababy(desc));

    }

    //页面显示初始化结束后获取评分弹窗配置
    private void fetchRateWindowConfig(){
        OkHttpUtil.getInstance_dababy().fetchRateConfig(this::onStarWindowConfigResponse_dababy);
    }

    //评分弹窗显示流程
    public void onStarWindowConfigResponse_dababy(){
        
        //1.活动弹窗
        if (RateAc_dababytiveWind_dababyowConfig.getInstance().isSwitch_dababy() &&
                DababyUtil.getActivedialogCount_dababy()< RateAc_dababytiveWind_dababyowConfig.getInstance().getNum_dababy()){
            new Rate_dababyActive_dababyDialog((AppCompatActivity) requireActivity()).show();
            return;
        }

        //2.评价弹窗
        if (Rate_dababyNormalW_dababyindowConfig.getInstance().isSwitch_dababy() &&
                DababyUtil.getNormaldialogCount_dababy()< Rate_dababyNormalW_dababyindowConfig.getInstance().getNum_dababy()){
            new RateNor_dababymalDialo_dababyg((AppCompatActivity) requireActivity()).show();
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"END","");
    }

}